package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    private WeChatProperties weChatProperties;

    @Autowired
    private UserMapper userMapper;

    @Override
    public User wxLogin(UserLoginDTO loginDTO) {
        //1、请求微信后台得到openId（用户唯一标识）
        String openId = getOpenId(loginDTO.getCode());
        //判断openid
        if (openId == null) {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }

        //2、通过openId从数据库中获取对应的用户
        User user = userMapper.getByOpenId(openId);
        //   如果数据库中没有该用户，需要插入该用户的数据（自动注册）
        if (user == null) {
            user = User.builder()
                    .openid(openId)
                    .createTime(LocalDateTime.now())
                    .build();
            //插入到数据库中
            userMapper.insert(user);
        }

        //3、用户数据返回到Controller

        return user;
    }

    /**
     * 获取用户的openid
     * @param code 前端发过来的授权码
     * @return openid
     */
    private String getOpenId(String code) {
        //微信后台的链接
        final String url = "https://api.weixin.qq.com/sns/jscode2session";
        //使用HttpClient去请求微信的后台，获取openid
        Map<String, String> map = new HashMap<>();
        map.put("appid",weChatProperties.getAppid());
        map.put("secret",weChatProperties.getSecret());
        map.put("js_code",code);
        map.put("grant_type","authorization_code");

        //访问微信后台，获取opendId
        String json = HttpClientUtil.doGet(url,map);
        /*
        {
            "session_key": "Cu26H5wUaS/Qgw02YFQRXQ==",
            "openid": "osvjO5aVgQ7zfjsXS-4vaF0g1BAk",
            "unionid": "o5PB1s3EX2yOdT445B8LpN0NZvH0"
        }
         */
        log.info("微信登录后台返回的结果：{}",json);
        //将字JSON字符串转换为JSON对象，再通过openId键去获取值
        JSONObject jsonObject = JSON.parseObject(json);
        String openid = jsonObject.getString("openid");
        log.info("openid解析成功：{}",openid);
        return openid;
    }
}
